<template>
  <view class="container">
    <!-- 顶部装饰 -->
    <view class="header-bg"></view>
    
    <!-- 头部导航 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <text class="back-icon">←</text>
      </view>
      <view class="header-content">
        <text class="header-title">个人信息</text>
        <text class="header-subtitle">完善您的资料</text>
      </view>
    </view>

    <!-- 表单卡片 -->
    <view class="form-card">
      <!-- 基本信息 -->
      <view class="section">
        <view class="section-title">基本信息</view>
        
        <view class="input-group">
          <text class="input-label">真实姓名</text>
          <input 
            class="input" 
            v-model="formData.real_name" 
            placeholder="请输入真实姓名"
            placeholder-class="input-placeholder"
          />
        </view>

        <view class="input-group">
          <text class="input-label">性别</text>
          <view class="gender-selector">
            <view 
              class="gender-option" 
              :class="{ active: formData.gender === 1 }"
              @click="formData.gender = 1"
            >
              <text class="gender-text">👨 男</text>
            </view>
            <view 
              class="gender-option" 
              :class="{ active: formData.gender === 0 }"
              @click="formData.gender = 0"
            >
              <text class="gender-text">👩 女</text>
            </view>
          </view>
        </view>

        <view class="input-group">
          <text class="input-label">年龄</text>
          <input 
            class="input" 
            type="number" 
            v-model="formData.age" 
            placeholder="请输入年龄"
            placeholder-class="input-placeholder"
          />
        </view>

        <view class="input-group">
          <text class="input-label">手机号</text>
          <input 
            class="input" 
            type="number" 
            v-model="formData.phone" 
            placeholder="请输入手机号"
            placeholder-class="input-placeholder"
            maxlength="11"
          />
        </view>
      </view>

      <!-- 医生专属信息 -->
      <view v-if="userType === 'doctor'" class="section">
        <view class="section-title">职业信息</view>
        
        <view class="input-group">
          <text class="input-label">医院</text>
          <input 
            class="input" 
            v-model="formData.hospital" 
            placeholder="请输入医院名称"
            placeholder-class="input-placeholder"
          />
        </view>

        <view class="input-group">
          <text class="input-label">科室</text>
          <input 
            class="input" 
            v-model="formData.department" 
            placeholder="请输入科室"
            placeholder-class="input-placeholder"
          />
        </view>

        <view class="input-group">
          <text class="input-label">职位</text>
          <input 
            class="input" 
            v-model="formData.position" 
            placeholder="请输入职位"
            placeholder-class="input-placeholder"
          />
        </view>
      </view>

      <!-- 提示信息 -->
      <view class="tips">
        <text class="tips-icon">💡</text>
        <text class="tips-text">请确保信息真实有效，以便更好地为您服务</text>
      </view>

      <!-- 保存按钮 -->
      <button class="save-btn" @click="saveProfile">
        <text class="btn-text">保存修改</text>
      </button>
    </view>
  </view>
</template>

<script>
import { updateUserProfile, getUserInfo } from '../../utils/api/auth.js';
import { getDoctorSelf, updateDoctorSelf } from '../../utils/api/doctor.js';
import { getLoginStatus, saveUserInfo } from '../../utils/auth.js';

export default {
  data() {
    return {
      userType: 'patient',
      formData: {
        real_name: '',
        gender: null,
        age: '',
        phone: '',
        hospital: '',
        department: '',
        position: ''
      }
    };
  },
  onLoad() {
    this.loadUserData();
  },
  onShow() {
    // 每次显示页面时重新加载数据
    this.loadUserData();
  },
  methods: {
    // 加载用户数据
    async loadUserData() {
      const loginStatus = getLoginStatus();
      this.userType = loginStatus.userType || 'patient';
      let userInfo = loginStatus.userInfo || {};
      
      console.log('[修改个人信息] 本地存储的用户数据:', userInfo);
      
      // 从API获取最新的用户信息
      try {
        let apiResponse;
        
        if (this.userType === 'doctor') {
          // 医生：调用医生专属接口
          apiResponse = await getDoctorSelf();
        } else {
          // 患者/管理员：调用通用接口
          apiResponse = await getUserInfo();
        }
        
        if (apiResponse && apiResponse.code === 200 && apiResponse.data) {
          userInfo = apiResponse.data;
          // 更新本地存储
          saveUserInfo(userInfo);
          console.log('[修改个人信息] 从API获取最新数据成功:', userInfo);
        }
      } catch (error) {
        console.warn('[修改个人信息] 从API获取数据失败，使用本地缓存:', error);
      }
      
      // 处理性别字段（可能是数字、字符串或其他格式）
      let genderValue = null;
      if (userInfo.gender !== undefined && userInfo.gender !== null) {
        // 转换为数字格式（1=男，0=女）
        if (userInfo.gender === 'male' || userInfo.gender === 1 || userInfo.gender === '1') {
          genderValue = 1;
        } else if (userInfo.gender === 'female' || userInfo.gender === 0 || userInfo.gender === '0') {
          genderValue = 0;
        } else {
          genderValue = parseInt(userInfo.gender);
        }
      }
      
      // 填充表单数据
      this.formData = {
        real_name: userInfo.real_name || userInfo.wechat_name || '',
        gender: genderValue,
        age: userInfo.age ? String(userInfo.age) : '',
        phone: userInfo.phone || '',
        hospital: userInfo.hospital || '',
        department: userInfo.department || '',
        position: userInfo.position || ''
      };
      
      console.log('[修改个人信息] 填充的表单数据:', this.formData);
    },
    
    // 保存修改
    async saveProfile() {
      // 验证必填字段
      if (!this.formData.real_name) {
        uni.showToast({
          title: '请输入真实姓名',
          icon: 'none'
        });
        return;
      }
      
      if (this.formData.gender === null) {
        uni.showToast({
          title: '请选择性别',
          icon: 'none'
        });
        return;
      }
      
      if (!this.formData.age) {
        uni.showToast({
          title: '请输入年龄',
          icon: 'none'
        });
        return;
      }
      
      // 验证手机号
      if (this.formData.phone && !/^1[3-9]\d{9}$/.test(this.formData.phone)) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        });
        return;
      }
      
      uni.showLoading({
        title: '保存中...',
        mask: true
      });
      
      try {
        // 准备提交数据
        const submitData = {
          real_name: this.formData.real_name,
          gender: parseInt(this.formData.gender),
          age: parseInt(this.formData.age),
          phone: this.formData.phone
        };
        
        // 如果是医生，添加医生专属字段
        if (this.userType === 'doctor') {
          submitData.hospital = this.formData.hospital;
          submitData.department = this.formData.department;
          submitData.position = this.formData.position;
        }
        
        // 根据用户类型调用不同的API
        let response;
        if (this.userType === 'doctor') {
          // 医生使用专属接口
          response = await updateDoctorSelf(submitData);
        } else {
          // 患者/管理员使用通用接口
          response = await updateUserProfile(submitData);
        }
        
        uni.hideLoading();
        
        if (response && response.code === 200) {
          // 更新本地存储的用户信息
          const loginStatus = getLoginStatus();
          const updatedUserInfo = {
            ...loginStatus.userInfo,
            ...submitData
          };
          saveUserInfo(updatedUserInfo);
          
          uni.showToast({
            title: '保存成功',
            icon: 'success',
            duration: 1500
          });
          
          // 延迟返回上一页
          setTimeout(() => {
            this.goBack();
          }, 1500);
        } else {
          uni.showToast({
            title: response.message || '保存失败',
            icon: 'none'
          });
        }
      } catch (error) {
        uni.hideLoading();
        console.error('保存个人信息失败:', error);
        uni.showToast({
          title: '保存失败，请重试',
          icon: 'none'
        });
      }
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack({
        delta: 1
      });
    }
  }
};
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: linear-gradient(180deg, #f0f9f7 0%, #f8f8f8 100%);
  position: relative;
}

/* 顶部装饰背景 */
.header-bg {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 300rpx;
  background: linear-gradient(135deg, #2db5a3 0%, #1e8e7e 100%);
  border-radius: 0 0 60rpx 60rpx;
  z-index: 0;
}

/* 头部导航 */
.header {
  position: relative;
  z-index: 10;
  padding: 60rpx 30rpx 40rpx;
  display: flex;
  align-items: center;
}

.back-btn {
  width: 70rpx;
  height: 70rpx;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(10rpx);
  margin-right: 20rpx;
}

.back-icon {
  font-size: 40rpx;
  color: #fff;
  font-weight: bold;
}

.header-content {
  flex: 1;
}

.header-title {
  font-size: 44rpx;
  font-weight: 700;
  color: #fff;
  display: block;
  letter-spacing: 2rpx;
}

.header-subtitle {
  font-size: 26rpx;
  color: rgba(255, 255, 255, 0.8);
  margin-top: 8rpx;
  display: block;
}

/* 表单卡片 */
.form-card {
  position: relative;
  z-index: 5;
  background: #fff;
  margin: -20rpx 30rpx 30rpx;
  padding: 40rpx 30rpx;
  border-radius: 30rpx;
  box-shadow: 0 8rpx 40rpx rgba(45, 181, 163, 0.12),
              0 2rpx 16rpx rgba(0, 0, 0, 0.08);
}

/* 分组区域 */
.section {
  margin-bottom: 50rpx;
}

.section:last-of-type {
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 30rpx;
  padding-left: 20rpx;
  border-left: 6rpx solid #2db5a3;
}

/* 输入组 */
.input-group {
  margin-bottom: 35rpx;
}

.input-label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 12rpx;
  display: block;
  padding-left: 5rpx;
}

.input {
  width: 100%;
  height: 88rpx;
  background: transparent;
  border: none;
  border-bottom: 2rpx solid #e8e8e8;
  padding: 0 10rpx;
  font-size: 32rpx;
  color: #333;
  transition: all 0.3s;
}

.input:focus {
  border-bottom-color: #2db5a3;
}

.input-placeholder {
  color: #bbb;
  font-size: 30rpx;
}

/* 性别选择器 */
.gender-selector {
  display: flex;
  gap: 20rpx;
  margin-top: 20rpx;
}

.gender-option {
  flex: 1;
  height: 88rpx;
  background: linear-gradient(135deg, #f8f9fa 0%, #f0f2f5 100%);
  border: 2rpx solid #e8e8e8;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.gender-option::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, #2db5a3 0%, #1e8e7e 100%);
  opacity: 0;
  transition: opacity 0.3s;
  z-index: 0;
}

.gender-option.active::before {
  opacity: 1;
}

.gender-text {
  font-size: 30rpx;
  color: #666;
  position: relative;
  z-index: 1;
  transition: color 0.3s;
}

.gender-option.active .gender-text {
  color: #fff;
  font-weight: 600;
}

/* 提示信息 */
.tips {
  background: linear-gradient(135deg, #fff8e1 0%, #ffecb3 100%);
  padding: 24rpx 28rpx;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;
  border-left: 6rpx solid #ffa726;
}

.tips-icon {
  font-size: 36rpx;
  margin-right: 16rpx;
}

.tips-text {
  flex: 1;
  font-size: 26rpx;
  color: #e65100;
  line-height: 1.6;
}

/* 保存按钮 */
.save-btn {
  width: 100%;
  height: 96rpx;
  background: linear-gradient(135deg, #2db5a3 0%, #1e8e7e 100%);
  border-radius: 48rpx;
  border: none;
  box-shadow: 0 8rpx 24rpx rgba(45, 181, 163, 0.35),
              0 4rpx 12rpx rgba(45, 181, 163, 0.25);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
}

.save-btn::after {
  border: none;
}

.save-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
  transition: left 0.5s;
}

.save-btn:active {
  transform: scale(0.98);
  box-shadow: 0 4rpx 16rpx rgba(45, 181, 163, 0.3),
              0 2rpx 8rpx rgba(45, 181, 163, 0.2);
}

.save-btn:active::before {
  left: 100%;
}

.btn-text {
  font-size: 34rpx;
  font-weight: 600;
  color: #fff;
  letter-spacing: 2rpx;
}
</style>

